from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from app.exceptions.base import BaseException as AppBaseException
from app.dao.base_dao import (
    DataDuplicateError,
    DataNotFoundError,
    DatabaseException,
    TransactionError
)
import logging

logger = logging.getLogger(__name__)


def setup_exception_handlers(app: FastAPI):
    """设置全局异常处理器"""
    
    @app.exception_handler(AppBaseException)
    async def app_exception_handler(request: Request, exc: AppBaseException):
        """处理应用自定义异常"""
        logger.error(f"应用异常: {exc.detail}")
        return JSONResponse(
            status_code=exc.status_code,
            content={"detail": exc.detail}
        )
        
    @app.exception_handler(Exception)
    async def general_exception_handler(request: Request, exc: Exception):
        """处理未捕获的通用异常"""
        logger.error(f"未捕获异常: {str(exc)}")
        return JSONResponse(
            status_code=500,
            content={"detail": "服务器内部错误"}
        )
        
    # 可以根据需要添加更多特定类型的异常处理器
    @app.exception_handler(DataDuplicateError)
    async def data_duplicate_exception_handler(request: Request, exc: DataDuplicateError):
        """处理数据重复异常"""
        logger.error(f"数据重复异常: {exc.args[0]}")
        return JSONResponse(
            content={
                "code": "D0001",
                "message": f" {exc.args[0]}"
                }
        )